How to use <br> Tag In Javascript

For basic line breaks, you can directly add <br> to your text easily.But for larger projects or when you need to add multiple line breaks, it is convenient to use more efficient methods.

Example: This illustrates a div element with two lines of text, separated by a line break, using JavaScript’s innerHTML property.

HTML
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
 <div id="myElement"></div>
    <script>
        let element = document.getElementById('myElement');
        element.innerHTML = 'lineone<br>linetwo';
    </script>
</body>
</html>

Output:

Output

How to Make a Breakline in JavaScript for innerHTML?

In JavaScript, while working with HTML you will frequently need to add line breaks whether building a complex or simple web application. In this article, you will learn to insert line breaks in JavaScript’s innerHTML.

These are the following approaches:

Table of Content

  • Using < br > Tag
  • Using Template Literals
  • By Creating Elements
  • Using CSS

Similar Reads

Using
Tag

For basic line breaks, you can directly add
to your text easily.But for larger projects or when you need to add multiple line breaks, it is convenient to use more efficient methods....

Using Template Literals

Template literals make adding line breaks cleaner and easier than string concatenation. They are used for multiline strings and also improves code readability. But remember, any indentation within template literals will show up in the output, which is not always favourable....

By Creating Elements

To insert line breaks, you can create a
element and append it to the target element of the webpage. This method is particularly useful while dealing with more complex DOM manipulation scenarios or when you need to insert line breaks dynamically based on specific conditions....

Using CSS

You can simply use CSS to control the spacing between lines instead of adding
tags directly. This method is more accessible and provides consistent line spacing. Simply use white-space: pre-line; CSS property to the element or its parent to automatically create line breaks according to the content provided....

Contact Us